package com.itcam.phaseiii.listener_;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Author:Cammy.Wu
 * Date:2024-05-11
 * Description:键盘监听
 */

public class KeyListenerTest {
    /**
     * 键盘事件：KeyListener
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) { // 键入某个按键时调用该方法

            }

            @Override
            public void keyPressed(KeyEvent e) { // 按下某个按键时调用该方法
                // 获取键盘的ascII码值
                int keyCode = e.getKeyCode();
                if(keyCode==37){
                    System.out.println("←");
                }else if(keyCode == 38){
                    System.out.println("↑");
                }else if(keyCode == 39){
                    System.out.println("→");
                }else if(keyCode == 40){
                    System.out.println("↓");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) { // 释放某个按键时调用该方法

            }
        });

        frame.setVisible(true);
    }
}
